<?php
/**     
  *
  * Copyright (c) 2009, Persistent Systems Limited
  *
  * Redistribution and use, with or without modification, are permitted 
  *  provided that the following  conditions are met:
  *   - Redistributions of source code must retain the above copyright notice, 
  *     this list of conditions and the following disclaimer.
  *   - Neither the name of Persistent Systems Limited nor the names of its contributors 
  *     may be used to endorse or promote products derived from this software 
  *     without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
/** 
 * ServiceBus/constants.inc
 */
require_once 'ServiceBus/constants.inc';
/** 
 * DotNetServicesEnvironment.php
 */
require_once 'DotNetServicesEnvironment.php';
/** 
 * ServiceBus/MessageBufferPolicy.php
 */
require_once 'ServiceBus/MessageBufferPolicy.php';
/** 
 * ACS/Scope.php
 */
require_once 'ACS/Scope.php';
/** 
 * ServiceBus/MessageBufferClient.php
 */
require_once 'ServiceBus/MessageBufferClient.php';
/** 
 * util/HttpWebProxy.php
 */
require_once 'util/HttpWebProxy.php';

/**
 * ServiceBusRequest for sending erquests to service bus
 * @access public
 */
class ServiceBusRequest
{
	/**
     * @access public
     * @var string 
     */
	public $authorization = "Required";
	/**
     * @access public
     * @var string 
     */
	public $maxMessageCount = "10";
	/**
     * @access public
     * @var string 
     */
	public $expiresAfter = "5";
	/**
     * @access public
     * @var string 
     */
	public $transportProtection = "None";
	/**
     * @access private
     * @var string 
     */
	private $_messageBufferName;
	/**
     * @access private
     * @var string 
     */
	private $_messageBufferUri;
	/**
     * @access private
     * @var string 
     */
	private $_scope;
	/**
     * @access private
     * @var string 
     */
	private $_httpWebProxy;	
   /**
	* HTTP prorocol for curl request
	*
	* @var string $requestProtocol
	* @access private
	*/
	const requestProtocol = 'http';
	
	/** 
	 * Class constructor
	 * @access public
	 * @param object $scope Scope class object 
	 * @param object $proxy HTTP proxy settings
	 * @param string $messageBufferName Message buffer name
	 */
	public function __construct($scope, $proxy, $messageBufferName)
	{
		$this->_scope = $scope;
		$this->_httpWebProxy = $proxy;
		$this->_messageBufferName = $messageBufferName;
	}
	
	/**
	`* This function deals with functionality related to message buffer
	 * @access public
	 * @param string $httpVerb GET|PUT|POST|DELETE
	 * @param string $requestUrl WEB service request URL
	 * @param array $requestBody POST data to web service
	 * @param array $headers Headers fields needed by web service
	 * @return string
	 */
	public function sendRequest($httpVerb, $requestUrl, $requestBody = array(), $headers)
	{		
		$policy = new MessageBufferPolicy();
		$policy->authorization = $this->authorization;
		$policy->maxMessageCount = $this->maxMessageCount;
		$policy->expiresAfter = $this->expiresAfter;
		$policy->transportProtection = $this->transportProtection;			
		
		//create message buffer with session id
		$this->_messageBufferUri = DotNetServicesEnvironment::getMessageBufferUri(self::requestProtocol,$this->_scope->getServiceNamespaceDomain(), session_id()) ;

		$responseClient = new MessageBufferClient($this->_messageBufferUri,$this->_scope,$policy,$this->_httpWebProxy); 
		//$responseClient->createMessageBuffer($policy);			
		
		//prepare request body and send to salesop via message buffer
		$clientReqDataArr = array('httpVerb'=>$httpVerb, 'url'=>$requestUrl, 'requestBody'=>$requestBody, 'headers'=>$headers, 'messageBufferName'=>session_id());
		 
		$messageInfo = $this->_prepareXmlRequestData($clientReqDataArr);		
		
		//create message buffer with supplied message buffer name
		$messageBufferUri = DotNetServicesEnvironment::getMessageBufferUri(self::requestProtocol ,$this->_scope->getServiceNamespaceDomain(), $this->_messageBufferName);

		$clientRequest = new MessageBufferClient($messageBufferUri,$this->_scope,$policy,$this->_httpWebProxy);
		 
		$clientRequest->sendMessage($messageInfo, 120);
		
		$atomResponseRaw=$responseClient->getMessage(120); 

		$atomBody = ""; 	
		preg_match("/<responseBody>(.*)<\/responseBody>/s", html_entity_decode($atomResponseRaw), $match);
		if(isset($match[1])){
			$atomBody = $match[1];
		} 
		
		$atomResponseCode = "";
		preg_match("/<responseCode>(.*)<\/responseCode>/s", html_entity_decode($atomResponseRaw), $match);
		if(isset($match[1])){
			$atomResponseCode = $match[1];
		}
		$atomResponse['response']=$atomBody;
		$atomResponse['http_code']=$atomResponseCode;
		return $atomResponse;
	}

	/**
	`* This function prepares the XMl formatted data from array passed
	 * @access public
	 * @param array $clientReqDataArr Request Data sent by client
	 * @return string XML formatted string 
	 */
	private function _prepareXmlRequestData($clientReqDataArr)
	{		
		$xmlFormattedString = "<request>";
		try {
			if(count($clientReqDataArr) > 0){
				$xmlFormattedString .= "<url>".urlencode($clientReqDataArr['url'])."</url>";
				$xmlFormattedString .= "<verb>".urlencode($clientReqDataArr['httpVerb'])."</verb>";
				$xmlFormattedString .= "<messageBufferName>".urlencode($clientReqDataArr['messageBufferName'])."</messageBufferName>";
				$xmlFormattedString .= "<body>".urlencode(http_build_query($clientReqDataArr['requestBody']))."</body>";
				$xmlFormattedString .= "<headers>";
				if(count($clientReqDataArr['headers']) > 0){
					foreach($clientReqDataArr['headers'] as $key=>$value){
						$xmlFormattedString .= "<header>";
						$xmlFormattedString .= "<name>".urlencode($key)."</name>";
						$xmlFormattedString .= "<value>".urlencode($value)."</value>";
						$xmlFormattedString .= "</header>";

					}
				}
				$xmlFormattedString .= "</headers>";
			}
			$xmlFormattedString .= "</request>";
		} catch(Exception $e){

		}
		return $xmlFormattedString;
	}
}
?>